package com.hieu.sms.utils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class BeanUtilities {

    /**
     * Retrieve a value from a property using
     * 
     * @param obj
     *            The object who's property you want to fetch
     * @param property
     *            The property name
     * @param defaultValue
     *            A default value to be returned if either a) The property is
     *            not found or b) if the property is found but the value is null
     * @return THe value of the property
     */
    @SuppressWarnings("unchecked")
    public static <T> T getProperty(Object obj, String property, T defaultValue) {
	T returnValue = (T) getProperty(obj, property);
	if (returnValue == null) {
	    returnValue = defaultValue;
	}

	return returnValue;

    }

    /**
     * Fetch a property from an object. For example of you wanted to get the foo
     * property on a bar object you would normally call {@code bar.getFoo()}.
     * This method lets you call it like
     * {@code BeanUtil.getProperty(bar, "foo")}
     * 
     * @param obj
     *            The object who's property you want to fetch
     * @param property
     *            The property name
     * @return The value of the property or null if it does not exist.
     */
    public static Object getProperty(Object obj, String property) {
	Object returnValue = null;

	try {
	    String methodName = "get" + property.substring(0, 1).toUpperCase()
		    + property.substring(1, property.length());
	    Class<?> clazz = obj.getClass();
	    Method method = clazz.getMethod(methodName,new Class[]{ null});
	    returnValue = method.invoke(obj,new Object[]{ null});
	} catch (Exception e) {
	    return null;
	}

	return returnValue;
    }

    /**
     * set value to properties of object
     * 
     * @param obj
     *            object that properties to be set value
     * @param property
     * @param value
     */
    public static void setProperty(Object obj, String property, Object value) {
	try {
	    String methodName = "set" + property.substring(0, 1).toUpperCase()
		    + property.substring(1, property.length());

	    Class<?> clazz = obj.getClass();
	    Field field = clazz.getDeclaredField(property);
	    Class<?> type = field.getType();
	    Method method = clazz.getMethod(methodName, new Class[] { type });
	    method.invoke(obj, new Object[] { value });
	} catch (Exception e) {
	    e.printStackTrace();
	}

    }

}
